import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Form,
  Input,
  Select,
  DatePicker,
  Modal,
  Card,
  Row,
  Col,
  Tag,
  Space,
  Tooltip,
  Badge,
  message,
  Popconfirm,
  Switch,
  Divider,
  Typography
} from 'antd';
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  ExportOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  FileTextOutlined,
  FolderOutlined,
  StarOutlined,
  StarFilled,
  LikeOutlined,
  ShareAltOutlined
} from '@ant-design/icons';
import { DocumentApi, DocumentCategoryApi, DocumentVO, DocumentPageParams, DocumentCategoryVO } from '../../api/document';
import DocumentForm from './components/DocumentForm';
import DocumentDetail from './components/DocumentDetail';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Title } = Typography;

const DocumentManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [documents, setDocuments] = useState<DocumentVO[]>([]);
  const [categories, setCategories] = useState<DocumentCategoryVO[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 搜索参数
  const [searchParams, setSearchParams] = useState<DocumentPageParams>({
    pageNo: 1,
    pageSize: 10,
  });

  // 模态框状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isDetailVisible, setIsDetailVisible] = useState(false);
  const [editingDocument, setEditingDocument] = useState<DocumentVO | null>(null);
  const [selectedDocument, setSelectedDocument] = useState<DocumentVO | null>(null);

  const [form] = Form.useForm();

  // 状态选项
  const statusOptions = [
    { label: '草稿', value: 0, color: 'default' },
    { label: '已发布', value: 1, color: 'success' },
    { label: '已下线', value: 2, color: 'error' },
  ];

  // 获取文档列表
  const fetchDocuments = async () => {
    setLoading(true);
    try {
      const response = await DocumentApi.getDocumentPage(searchParams);
      setDocuments(response.list);
      setPagination(prev => ({
        ...prev,
        total: response.total,
        current: searchParams.pageNo,
        pageSize: searchParams.pageSize,
      }));
    } catch (error) {
      message.error('获取文档列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const response = await DocumentCategoryApi.getCategoryTree();
      setCategories(response);
    } catch (error) {
      message.error('获取分类列表失败');
    }
  };

  useEffect(() => {
    fetchDocuments();
    fetchCategories();
  }, [searchParams]);

  // 搜索处理
  const handleSearch = () => {
    const values = form.getFieldsValue();
    setSearchParams({
      ...searchParams,
      pageNo: 1,
      title: values.title,
      categoryId: values.categoryId,
      author: values.author,
      status: values.status,
      createTime: values.createTime,
    });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setSearchParams({
      pageNo: 1,
      pageSize: 10,
    });
  };

  // 分页处理
  const handleTableChange = (page: number, pageSize?: number) => {
    setSearchParams({
      ...searchParams,
      pageNo: page,
      pageSize: pageSize || 10,
    });
  };

  // 新增文档
  const handleAdd = () => {
    setEditingDocument(null);
    setIsModalVisible(true);
  };

  // 编辑文档
  const handleEdit = (record: DocumentVO) => {
    setEditingDocument(record);
    setIsModalVisible(true);
  };

  // 查看详情
  const handleViewDetail = (record: DocumentVO) => {
    setSelectedDocument(record);
    setIsDetailVisible(true);
    // 增加浏览量
    DocumentApi.increaseViewCount(record.id);
  };

  // 删除文档
  const handleDelete = async (id: number) => {
    try {
      await DocumentApi.deleteDocument(id);
      message.success('删除成功');
      fetchDocuments();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 更新状态
  const handleUpdateStatus = async (id: number, status: number) => {
    try {
      await DocumentApi.updateDocumentStatus(id, status);
      message.success('状态更新成功');
      fetchDocuments();
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  // 置顶文档
  const handleTop = async (id: number, isTop: boolean) => {
    try {
      await DocumentApi.topDocument(id, isTop);
      message.success(isTop ? '置顶成功' : '取消置顶成功');
      fetchDocuments();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 点赞文档
  const handleLike = async (id: number) => {
    try {
      await DocumentApi.likeDocument(id);
      message.success('点赞成功');
      fetchDocuments();
    } catch (error) {
      message.error('点赞失败');
    }
  };

  // 导出文档
  const handleExport = async () => {
    try {
      await DocumentApi.exportDocument(searchParams);
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    }
  };

  // 保存文档
  const handleSave = () => {
    fetchDocuments();
    setIsModalVisible(false);
  };

  // 表格列定义
  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      render: (text: string, record: DocumentVO) => (
        <Space>
          <FileTextOutlined />
          <a onClick={() => handleViewDetail(record)}>{text}</a>
          {record.isTop && <StarFilled style={{ color: '#faad14' }} />}
        </Space>
      ),
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      width: 120,
      render: (text: string) => (
        <Tag icon={<FolderOutlined />} color="blue">
          {text}
        </Tag>
      ),
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: number) => {
        const option = statusOptions.find(opt => opt.value === status);
        return <Tag color={option?.color}>{option?.label}</Tag>;
      },
    },
    {
      title: '浏览量',
      dataIndex: 'viewCount',
      key: 'viewCount',
      width: 80,
      render: (count: number) => (
        <Badge count={count} showZero color="#52c41a" />
      ),
    },
    {
      title: '点赞数',
      dataIndex: 'likeCount',
      key: 'likeCount',
      width: 80,
      render: (count: number) => (
        <Badge count={count} showZero color="#1890ff" />
      ),
    },
    {
      title: '发布时间',
      dataIndex: 'publishTime',
      key: 'publishTime',
      width: 150,
      render: (time: string) => time ? new Date(time).toLocaleString() : '-',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      render: (time: string) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right' as const,
      render: (_: any, record: DocumentVO) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="link"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="link"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title={record.isTop ? '取消置顶' : '置顶'}>
            <Button
              type="link"
              icon={record.isTop ? <StarFilled /> : <StarOutlined />}
              onClick={() => handleTop(record.id, !record.isTop)}
              style={{ color: record.isTop ? '#faad14' : undefined }}
            />
          </Tooltip>
          <Tooltip title="点赞">
            <Button
              type="link"
              icon={<LikeOutlined />}
              onClick={() => handleLike(record.id)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这篇文档吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="link"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Title level={4}>文档管理</Title>
        
        {/* 搜索表单 */}
        <Form
          form={form}
          layout="inline"
          style={{ marginBottom: '16px' }}
          onFinish={handleSearch}
        >
          <Form.Item name="title" label="标题">
            <Input placeholder="请输入文档标题" allowClear />
          </Form.Item>
          <Form.Item name="categoryId" label="分类">
            <Select placeholder="请选择分类" allowClear style={{ width: 150 }}>
              {categories.map(category => (
                <Option key={category.id} value={category.id}>
                  {category.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="author" label="作者">
            <Input placeholder="请输入作者" allowClear />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" allowClear style={{ width: 120 }}>
              {statusOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="createTime" label="创建时间">
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button onClick={handleReset} icon={<ReloadOutlined />}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        {/* 操作按钮 */}
        <Row justify="space-between" style={{ marginBottom: '16px' }}>
          <Col>
            <Space>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                新增文档
              </Button>
              <Button icon={<ExportOutlined />} onClick={handleExport}>
                导出
              </Button>
            </Space>
          </Col>
        </Row>

        {/* 文档表格 */}
        <Table
          columns={columns}
          dataSource={documents}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
            onChange: handleTableChange,
            onShowSizeChange: handleTableChange,
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 新增/编辑模态框 */}
      <Modal
        title={editingDocument ? '编辑文档' : '新增文档'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
        destroyOnClose
      >
        <DocumentForm
          document={editingDocument}
          categories={categories}
          onSave={handleSave}
          onCancel={() => setIsModalVisible(false)}
        />
      </Modal>

      {/* 详情模态框 */}
      <Modal
        title="文档详情"
        open={isDetailVisible}
        onCancel={() => setIsDetailVisible(false)}
        footer={null}
        width={1000}
        destroyOnClose
      >
        <DocumentDetail
          document={selectedDocument}
          onEdit={(doc: DocumentVO) => {
            setIsDetailVisible(false);
            handleEdit(doc);
          }}
        />
      </Modal>
    </div>
  );
};

export default DocumentManagement;